#!/bin/bash
# 菜单导入V2 JSON响应修复验证脚本
# 确保所有接口永远返回JSON格式，前端不会因为非JSON响应崩溃

set -e

echo "=== 菜单导入V2 JSON响应修复验证开始 ==="
echo "时间: $(date)"

# 配置
BASE_URL="http://localhost:3001"
TOKEN="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjEsImVtYWlsIjoiYWRtaW5AZXhhbXBsZS5jb20iLCJtZW1iZXJzaGlwTGV2ZWwiOiJhZG1pbiIsImlhdCI6MTc1Njk5NDExNywiZXhwIjoxNzU3MDgwNTE3LCJpc3MiOiJjdS1tci1idWxsLWFwaSJ9.kz4cuvnqVjzTJtMmh582rX-VPzTEWdmTHksEoVf0nFU"
TEST_DIR="/tmp/json_response_test"

# 创建测试目录
mkdir -p $TEST_DIR
cd $TEST_DIR

echo "\n=== 测试1: 任务状态查询 - 不存在的任务 ==="
echo "1.1 测试不存在的UUID任务"
curl -sS -D headers1.txt $BASE_URL/api/menu-import/v2/jobs/550e8400-e29b-41d4-a716-446655440000 \
  -H "Authorization: Bearer $TOKEN" \
  --max-time 10 > job_not_found.json
echo "✓ 不存在任务测试完成"
echo "Content-Type: $(grep -i 'content-type' headers1.txt || echo 'Not found')"
echo "响应内容:"
cat job_not_found.json | jq .

echo "\n1.2 测试无效UUID格式"
curl -sS -D headers2.txt $BASE_URL/api/menu-import/v2/jobs/invalid-job-id \
  -H "Authorization: Bearer $TOKEN" \
  --max-time 10 > job_invalid_uuid.json
echo "✓ 无效UUID测试完成"
echo "Content-Type: $(grep -i 'content-type' headers2.txt || echo 'Not found')"
echo "响应内容:"
cat job_invalid_uuid.json | jq .

echo "\n=== 测试2: 创建真实任务并查询 ==="
echo "2.1 下载模板"
curl -sS $BASE_URL/api/menu-import/v2/template/menu.xlsx \
  -H "Authorization: Bearer $TOKEN" \
  -o test_template.xlsx --max-time 30
echo "✓ 模板下载完成，文件大小: $(wc -c < test_template.xlsx) 字节"

echo "\n2.2 上传模板创建任务"
curl -sS -X POST $BASE_URL/api/menu-import/v2/validate \
  -H "Authorization: Bearer $TOKEN" \
  -F "file=@test_template.xlsx" \
  --max-time 30 > validate_response.json
echo "✓ 上传验证完成"
echo "验证响应:"
cat validate_response.json | jq .

# 提取job_id
JOB_ID=$(cat validate_response.json | jq -r '.job_id')
echo "\n获取到任务ID: $JOB_ID"

if [ "$JOB_ID" != "null" ] && [ -n "$JOB_ID" ]; then
  echo "\n2.3 查询真实任务状态"
  for i in {1..5}; do
    echo "查询第 $i 次..."
    curl -sS -D "headers_real_$i.txt" $BASE_URL/api/menu-import/v2/jobs/$JOB_ID \
      -H "Authorization: Bearer $TOKEN" \
      --max-time 10 > "job_status_real_$i.json"
    
    echo "Content-Type: $(grep -i 'content-type' "headers_real_$i.txt" || echo 'Not found')"
    echo "响应内容:"
    cat "job_status_real_$i.json" | jq .
    
    STATUS=$(cat "job_status_real_$i.json" | jq -r '.status')
    echo "任务状态: $STATUS"
    
    if [ "$STATUS" = "validated" ] || [ "$STATUS" = "failed" ] || [ "$STATUS" = "succeeded" ]; then
      echo "✓ 任务完成，最终状态: $STATUS"
      break
    fi
    
    sleep 2
  done
else
  echo "❌ 无法获取有效的job_id，跳过真实任务测试"
fi

echo "\n=== 测试3: 模拟系统错误 ==="
echo "3.1 测试无认证访问"
curl -sS -D headers_no_auth.txt $BASE_URL/api/menu-import/v2/jobs/550e8400-e29b-41d4-a716-446655440000 \
  --max-time 10 > job_no_auth.json 2>/dev/null || echo "请求完成（可能有错误）"
echo "✓ 无认证测试完成"
echo "Content-Type: $(grep -i 'content-type' headers_no_auth.txt || echo 'Not found')"
echo "响应内容:"
cat job_no_auth.json | jq . 2>/dev/null || cat job_no_auth.json

echo "\n3.2 测试错误Token"
curl -sS -D headers_bad_token.txt $BASE_URL/api/menu-import/v2/jobs/550e8400-e29b-41d4-a716-446655440000 \
  -H "Authorization: Bearer invalid-token" \
  --max-time 10 > job_bad_token.json 2>/dev/null || echo "请求完成（可能有错误）"
echo "✓ 错误Token测试完成"
echo "Content-Type: $(grep -i 'content-type' headers_bad_token.txt || echo 'Not found')"
echo "响应内容:"
cat job_bad_token.json | jq . 2>/dev/null || cat job_bad_token.json

echo "\n=== 验收检查 ==="
echo "\n检查所有响应是否为有效JSON:"

# 检查JSON有效性的函数
check_json() {
  local file=$1
  local name=$2
  if [ -f "$file" ]; then
    if jq . "$file" >/dev/null 2>&1; then
      echo "✓ $name: 有效JSON"
      # 检查是否包含必要字段
      if jq -e '.success != null and .status != null' "$file" >/dev/null 2>&1; then
        echo "  - 包含必要字段 (success, status)"
      else
        echo "  - ⚠️ 缺少必要字段"
      fi
      # 检查requestId
      if jq -e '.requestId != null' "$file" >/dev/null 2>&1; then
        echo "  - 包含requestId"
      else
        echo "  - ⚠️ 缺少requestId"
      fi
    else
      echo "✗ $name: 无效JSON"
      echo "  内容预览: $(head -c 200 "$file")"
    fi
  else
    echo "✗ $name: 文件不存在"
  fi
}

check_json "job_not_found.json" "不存在任务"
check_json "job_invalid_uuid.json" "无效UUID"
check_json "validate_response.json" "验证响应"
if [ "$JOB_ID" != "null" ] && [ -n "$JOB_ID" ]; then
  check_json "job_status_real_1.json" "真实任务状态"
fi
check_json "job_no_auth.json" "无认证访问"
check_json "job_bad_token.json" "错误Token"

echo "\n=== Content-Type检查 ==="
echo "检查所有响应的Content-Type是否正确:"

check_content_type() {
  local file=$1
  local name=$2
  if [ -f "$file" ]; then
    local ct=$(grep -i 'content-type' "$file" | head -1)
    if echo "$ct" | grep -i 'application/json' >/dev/null; then
      echo "✓ $name: 正确的Content-Type"
    else
      echo "✗ $name: 错误的Content-Type - $ct"
    fi
  else
    echo "✗ $name: 头文件不存在"
  fi
}

check_content_type "headers1.txt" "不存在任务"
check_content_type "headers2.txt" "无效UUID"
if [ "$JOB_ID" != "null" ] && [ -n "$JOB_ID" ]; then
  check_content_type "headers_real_1.txt" "真实任务状态"
fi
check_content_type "headers_no_auth.txt" "无认证访问"
check_content_type "headers_bad_token.txt" "错误Token"

echo "\n=== 测试完成 ==="
echo "测试结果保存在: $TEST_DIR"
echo "主要文件:"
ls -la *.json *.txt 2>/dev/null | head -10

echo "\n=== 总结 ==="
echo "1. JSON格式: 所有响应都应该是有效的JSON"
echo "2. Content-Type: 所有响应都应该包含 application/json"
echo "3. 统一结构: 所有响应都应该包含 success, status, requestId 字段"
echo "4. 错误处理: 系统错误应该返回 system_error 字段而不是堆栈信息"

echo "\n测试完成时间: $(date)"